<?php
/**
 *
 * Enter description here ...
 * @param $nid NodeId của
 */
function _api_select_top_user($nid){
	$sql  = "SELECT * FROM {lastbuyer_transaction} WHERE nid=%d AND in_day=%d AND status=%d ORDER BY ref_date DESC, buy_date DESC";
	$query = pager_query($sql, 11,0,NULL,$nid,0,1);
	// Process the query...
	while ($record = db_fetch_object($query)) {
		$rows[] =$record;
	}
	print(json_encode($rows));
	module_invoke_all('exit');
	exit(0);
}
function _api_get_point_user_in_product($nid,$uid){
	$sql  = "SELECT SUM(point) FROM {lastbuyer_transaction} WHERE nid=%d AND uid=%d";
	print db_result(db_query($sql,$nid,$uid));
	module_invoke_all('exit');
	exit(0);
}
/**
 *
 * Hiển thị Form để cập nhật thứ hạng của người chơi dùng trên tool admin
 * @param $form_state
 * @return trả về  thông tin của 1 form
 */
function _api_update_index_form(&$form_state){
	$form['uid'] = array(
      '#type' => 'textfield', 
      '#title' => t('User id'), 
      '#default_value' => '',
      '#required' => TRUE, 
	);
	$form['method'] = array(
      '#type' => 'select', 
      '#title' => t('Method'), 
      '#default_value' => 1,
      '#options' => array(0=>'json',1=>'form'),
	);
	$form['nid']=array(
      '#type' => 'textfield', 
      '#title' => t('Product id'), 
      '#default_value' => '', 
  	  '#required' => TRUE, 
	);
	$form['idx'] = array(
      '#type' => 'textfield', 
      '#title' => t('index'), 
      '#default_value' => '',
	);
	$form['point'] = array(
      '#type' => 'textfield', 
      '#title' => t('Point'), 
      '#default_value' => '',
	);
	$form['ref_date'] = array(
      '#type' => 'textfield', 
      '#title' => t('Ref date'), 
      '#default_value' => '',
	);
	$form['rank'] = array(
      '#type' => 'textfield', 
      '#title' => t('Rank'), 
      '#default_value' => '',
	);

	$form['buy_date'] = array(
      '#type' => 'textfield', 
      '#title' => t('Buy date'), 
      '#default_value' => '',
	);
	$form['section'] = array(
      '#type' => 'select', 
      '#title' => t('section'), 
      '#default_value' => 0,
      '#options' => array(2=>'Mo',3=>'Tu',4=>'We',5=>'Th',6=>'Fr',7=>'Sa',1=>'Su',0=>'Al'),
	);
	$form['submit'] = array('#type' => 'submit', '#value' => t('Update'));
	return $form;
}
/**
 *
 * Xử lý cập nhật thứ hạng của người chơi
 * @param $form
 * @param $form_state
 *
 */
function _api_update_index_form_submit($form, &$form_state) {
	$uid =$form_state['values']['uid'];
	$method =$form_state['values']['method'];
	$nid =$form_state['values']['nid'];
	$idx =$form_state['values']['idx'];
	$point =$form_state['values']['point'];
	//TODO tinh lai point trong bang bonus_point
	$sql =  "SELECT SUM(point) FROM {bonus_point} WHERE uid = %d AND status= %d AND group_id=%d";
	$point =  db_result(db_query($sql,$uid,1,$nid));
	$ref_date =$form_state['values']['ref_date'];
	$buy_date =$form_state['values']['buy_date'];
	$rank =$form_state['values']['rank'];
	$section =$form_state['values']['section'];
	$trace_id =$form_state['values']['trace_id'];
	

	$node = node_load($nid);
	$title =  $node->title;

	$user = user_load($uid);
	$name =  $user->name;

	$sql ="INSERT INTO {lastbuyer_records} (nid,rank,title,name,uid,idx,point,ref_date,buy_date,section,trace_id) VALUES(%d,%d,'%s','%s',%d,%d,%d,%d,%d,%d,'%s')";
	$result = db_query($sql,$nid,$rank,$title,$name,$uid,$idx,$point,$ref_date,$buy_date,$section,$trace_id);
	if(!$method){
		if($result == FALSE){
			print "FAIL";
			module_invoke_all('exit');
			exit(0);
		}else{
			print "SUCCESS";
			module_invoke_all('exit');
			exit(0);
		}
	}

}
function _get_status_array(){
	return  array(
	-1 => t('--- All ---'),
	0 => t('Just buy'),
	1 => t('Updated trace id'),
	2 => t('Buy successfully'),
	3 => t('Invalid transaction'),
	);
}
function _get_in_day_status_array(){
	return array(
	-1 => t('--- All ---'),
	0 => t('Processed for day'),
	1 => t('In day'),
	);
}
/**
 *
 * Hiển thị form cho phép import file excel từ baokim
 * @param $form_state
 */
function _api_admin_import_trace_form(&$form_state){
	$form['trace_id'] = array(
      '#type' => 'textfield', 
      '#title' => t('Trace id'), 
      '#default_value' => '',
      '#required' => TRUE, 
	);
	$form['method'] = array(
      '#type' => 'select', 
      '#title' => t('Method'), 
      '#default_value' => 1,
      '#options' => array(0=>'json',1=>'form'),
	);
	$form['date']=array(
      '#type' => 'textfield', 
      '#title' => t('Date'), 
      '#default_value' => '', 
  	  '#required' => TRUE, 
	  '#description' => t('YYYY,MM,dd,HH,mm,ss'),
	);
	$form['section'] = array(
      '#type' => 'select', 
      '#title' => t('section'), 
      '#default_value' => 0,
      '#options' => array(2=>'Mo',3=>'Tu',4=>'We',5=>'Th',6=>'Fr',7=>'Sa',1=>'Su',0=>'Al'),
	);
	$form['last'] = array(
      '#type' => 'select', 
      '#title' => t('Last import'), 
      '#default_value' => 0,
      '#options' => array(1=>'Yes',0=>'No'),
	);
	$form['submit'] = array('#type' => 'submit', '#value' => t('Update'));
	return $form;
}
/**
 *
 * Xử lý phần import file từ baokim
 * @param $form
 * @param $form_state
 */
function _api_admin_import_trace_form_submit($form, &$form_state) {
	$trace_id =$form_state['values']['trace_id'];
	$date=$form_state['values']['date'];
	$last=$form_state['values']['last'];
	$method = $form_state['values']['method'];
	$section = $form_state['values']['section'];
	
	//search transaction by trace_id
	$sql  = "SELECT * FROM {lastbuyer_transaction} WHERE trace_id='%s'";
	$running_batch  = FALSE;
	$result = TRUE;
	if ($r = db_fetch_array(db_query($sql,$trace_id))) {
		//TODO thay doi thanh kiem tra tu 8h den 9h toi
        //thay doi thanh kiem tra tu 8h den 9h toi
        //DONE
		if(lb_is_running_batch()){
			$sql  = "INSERT INTO {lastbuyer_batch} (status,running_date) VALUES(%d,%d)";
			$running_batch = db_query($sql,1,time());
		}
		if($running_batch!=FALSE){
			$nid  =  $r['nid'];
			//update in_day status to 0, update ref_date
			$dateArray = explode(',',$date);
			$timezone = variable_get('date_default_timezone', 0);
			$ref_date = gmmktime($dateArray[3],$dateArray[4],$dateArray[5],$dateArray[1],$dateArray[2],$dateArray[0]) -$timezone;
			$sql = "UPDATE {lastbuyer_transaction} SET in_day=%d,ref_date=%d,status=%d WHERE trace_id='%s'";
			$result = db_query($sql,0,$ref_date,2,$trace_id);
			if( $result != FALSE) {
				//update lastbuyer_product: number_of_buy=number_of_buy+1
				$sql = "UPDATE {lastbuyer_product} SET number_of_buy=number_of_buy+1 WHERE nid=%d";
				db_query($sql,$nid);
				//TODO insert to bonus_point
				//neu da co 1 dong du lieu cua cung 1 ngay thi ko insert
				$sql  = "SELECT COUNT(*) FROM {bonus_point} WHERE group_id =%d AND type=%d AND section=%d";
				if(db_result(db_query($sql,$nid,0,$section))==0){
				  $sql =  "INSERT INTO {bonus_point} (point,status,uid,type,group_id,ref_id,create_date,section,description) VALUES(%d,%d,%d,%d,%d,%d,%d,%d,'%s')";
				  db_query($sql,1,1,$r['uid'],0,$nid,$r['tid'],time(),$section,serialize(array('Add @point point for buy success product: !nid with trace: @id',array('@point'=> 1,'@nid'=>$nid,'@id'=>$r['tid']))));
				}
			}
		}

	}
	if($running_batch && $last == 1){
		//update lastbuyer_batch: status=NULL
		$sql = "UPDATE {lastbuyer_batch} SET status=NULL WHERE status=%d";
		db_query($sql,1);
	}
	if(!$method){
		if($result == FALSE){
			module_invoke_all('exit');
			print "FAIL";
			exit(0);
		}else{
			print "SUCCESS";
			module_invoke_all('exit');
			exit(0);
		}
	}
}

?>